package com.cychat.mall.service.impl;

import com.Cychat.commons.entity.pojo.OrderDetail;
import com.Cychat.commons.entity.pojo.Orders;
import com.Cychat.commons.entity.pojo.Product;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cychat.mall.mapper.OrderDetailMapper;
import com.cychat.mall.mapper.OrdersMapper;
import com.cychat.mall.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Auther: 刘俊  <br/>
 * Date: 2025-11-8:下午 3:20  <br/>
 * Description: 支付回调服务实现类
 */
@Service
public class PayCallbackService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ProductMapper productMapper;

    @Transactional(rollbackFor = Exception.class)
    public void onPaySuccess(String orderId) {
        // 检查订单是否待支付
        Orders orders = ordersMapper.selectById(orderId);
        if (orders.getOrderStatus() != 0) {
            return;
        }

        // 更新订单状态为已支付
        orders.setOrderStatus(1);
        ordersMapper.updateById(orders);

        // 扣减 DB 库存
        List<OrderDetail> details = orderDetailMapper.selectList(
                new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, orderId));
        for (OrderDetail d : details) {
            Product product = productMapper.selectById(d.getProductId());
            product.setStock(product.getStock() - d.getQuantity());
            product.setSales(product.getSales() + d.getQuantity());
            product.setUpdateTime(new Date());
            int updated = productMapper.updateById(product);
            if (updated == 0) {
                throw new RuntimeException("DB库存异常，商品ID: " + d.getProductId());
            }
        }
    }
}
